package com.shengxi.mqtt;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 1. @author WXY
 2. @date 2022/6/29 20:42
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "mqtt")
public class MqttConfiguration {

    private String host;
    private String username;
    private String password;
    private String clientId;
    private Integer timeOut;
    private Integer keepAlive;

    /**
     * 注入spring
     * @return
     */
    @Bean
    public MyMqttClient myMqttClient() {
        MyMqttClient myMqttClient = new MyMqttClient(host, username, password, clientId, timeOut, keepAlive);
        for (int i = 0; i < 10; i++) {
            try {
                myMqttClient.connect();
                return myMqttClient;
            } catch (MqttException e) {
                log.error("MQTT connect exception,connect time = " + i);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return myMqttClient;
    }
}
